package com.bupt.kgplatform.common;

import com.alibaba.fastjson.JSONObject;
import com.bupt.kgplatform.entity.pojo.OperateLog;
import com.bupt.kgplatform.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * ClassName:LogAspect
 * Package:com.example.blackjavaweb.aop
 * Description:
 *
 * @Author QIQI_1999
 * @Creat 2023/9/18 10:28
 * @Version 1.0
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.bupt.kgplatform.common.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //插入基本信息建立，名称和OperateLog属性名称一致
        //注：操作人id信息，后续设置cookie或者令牌技术后完成
        LocalDateTime operateTime = LocalDateTime.now();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();
        //调用原始方法
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        String returnValue = JSONObject.toJSONString(result);
        if(methodName.startsWith("search")){
            returnValue = "查询语句不记录返回值";
        }
        Long costTime = end - begin;



        OperateLog operateLog = new OperateLog(null,1,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);

        return result;
    }

}
